﻿using System;
using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Rows
{
    /// <summary>
    /// Writes the contents of the given object into the database.
    /// </summary>
    public static class InsertCommand
    {
        private const string Sql = @"INSERT INTO {0} ({1}) VALUES ({2}); SELECT LAST_INSERT_ID();";

        /// <summary>
        /// Writes the contents of the given object into the database.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <param name="connection">The connection.</param>
        /// <returns></returns>
        public static int Execute<T>(T result, Connection connection)
        {
            var tableName = TableNameFinder.Find(result.GetType());
            var columns = ColumnFinder.Find(typeof(T), result);

            foreach (var column in columns)
            {
                // Don't insert PK if auto assigned
                if (column.PrimaryKey && column.AutoIncrement) continue;

                // Don't insert null values
                if (column.Value == null) continue;
            }

            var id = Convert.ToInt32(connection.ExecuteScalar(Sql, columns.ToDbParameters(), tableName, columns.ToInsertColumnsSql(), columns.ToInsertParametersSql()));

            return id;
        }
    }
}